package com.ludomancy.starwave;

import java.util.Properties;

import com.ludomancy.gamelib.DataStorage;
import com.ludomancy.gamelib.GameApplet;
import com.ludomancy.gamelib.GameCanvas;
import com.ludomancy.gamelib.Sound;

public class StarWaveApplet extends GameApplet
{
	public static StarWaveWidget mainWidget;
	private GameWonWidget gameWonWidget;
	public static StarWaveApplet app;
	
	int level = 0;
	
	public void init()
	{
		super.init(new StarwaveTheme());
		app = this;
		
		// preloading
		Settings.getExplosion(1);
		Settings.getExplosion(-1);
		new Sound("blow.wav");
		Sound.soundActivated = true;
		
		//TODO: remove
		LevelManager.loadMissions();

		// should we load a savegame?
		try
		{
			Properties props = DataStorage.load("starwave");
			String levelString = (String)props.get("level");
			level = Integer.parseInt(levelString);
			if(level < 0 || level >= LevelManager.getLevelCount())
			{
				// no luck
				level = 0;
			}
		}
		catch(Exception e)
		{
		}
		resetGame(true, null);
	}
	
	public void resetGame(boolean showBriefing, int[][] initialSetup)
	{
		// create the game
		new Game(level);
		
		// create the UI
		gameCanvas.destroyWidget(mainWidget);
		mainWidget = new StarWaveWidget(null, getBounds(), initialSetup, showBriefing);
		gameCanvas.showWidget(mainWidget);
	}
	
	public void restart()
	{
		level = 0;
		saveData();
		resetGame(true, null);
	}
	
	private void saveData()
	{
		// save level
		Properties props = new Properties();
		props.put("level", String.valueOf(level));
		DataStorage.save("starwave", props);		
	}

	public void nextLevel()
	{
		level++;
		if(LevelManager.isLastLevel(level))
		{
			level = 0;
			saveData();
			// show winning brief
			gameWonWidget = new GameWonWidget(null);
			GameCanvas.screen.showWidget(gameWonWidget);
		}
		else
		{
			saveData();
			resetGame(true, null);
		}
	}

}
